import pygtk
pygtk.require('2.0')
import gtk
# import os, sy
import os, sys

from mokoconv.util.sqlutil import SqlUtil
from mokoconv.gui.modaldialog import ModalDialog
from mokoconv.gui.keyboard import KeyBoard

class MokoConvWindow:
    
    def clean(self, widget):
        self.entryValue.set_text("")
        
    def isNumber(self, value):
        try:
            float(value)
            return True
        except ValueError:
            return False
    
    
    def convert(self, widget):
        
        # check entry
        if len(self.entryValue.get_text()) == 0:
            modal = ModalDialog("No Entry")
            return

        if self.isNumber(self.entryValue.get_text()) == False:
            modal = ModalDialog("No valid Number")
            return
        
        val = self.sqlUtil.getUnitRelation(self.unitsFrom[self.comboBoxFrom.get_active()].id_unit, self.unitsTo[self.comboBoxTo.get_active()].id_unit);
        # we have to replace tag > <VAL>
        print val
        val = val.replace("<VAL>",self.entryValue.get_text())
        print val
        # trick a moltiplication with 1.0 force ther result in float and not in integer
        ret = eval("1.0 * " + val)
        #self.entryValue.get_text()
        self.labelResult.set_text(str(ret))

    def changeCategory(self, widget):
        #print(widget.get_active())

        # remove_text raise signal "changed"
        # but we are not interested now in loadsItemsTo method
        self.noSignalFrom = True 
        for x in range(0, self.countFromItems):
            print "remove " + self.unitsFrom[x].description
            self.comboBoxFrom.remove_text(0)
        # enable signal
        self.noSignalFrom = False
        
        # load units
        self.unitsFrom = self.sqlUtil.loadUnits(self.categories[widget.get_active()].id_category, None)
        
        for unit in self.unitsFrom:
            # print unit.description
            print "append >> " + unit.description
            self.comboBoxFrom.append_text(unit.description)
        
        self.countFromItems = len(self.unitsFrom)
        if self.countFromItems != 0:
            # select the first item trigger loadItemsTo
            self.comboBoxFrom.set_active(0)
    
    def loadItemsTo(self, widget):

        if self.noSignalFrom == True:
            return None
        
        self.unitsTo = self.sqlUtil.loadUnits(self.categories[self.comboBoxCategory.get_active()].id_category, self.unitsFrom[self.comboBoxFrom.get_active()].id_unit)

        for x in range(0, self.countToItems):
            self.comboBoxTo.remove_text(0)
        
        for unit in self.unitsTo:
            #print unit.description
            self.comboBoxTo.append_text(unit.description)
        
        self.countToItems = len(self.unitsTo)
        if self.countToItems != 0:
            # select the first item 
            self.comboBoxTo.set_active(0)
        
        
        
    def delete_event(self, widget, event, data=None):
        # If you return FALSE in the "delete_event" signal handler, 
        # GTK will emit the "destroy" signal. Returning TRUE means you don't want the window to be destroyed.
        # This is useful for popping up 'are you sure you want to quit?' type dialogs.
        print("delete event occurred")
        
        # Change FALSE to TRUE and the main window will not be destroyed with a "delete_event".
        return False

    def destroy(self, widget, data=None):
        print("destroy signal occurred")
        gtk.main_quit()
        
    def buildLayout(self, keyPadMode):
        
        # vbox 
        vbox = gtk.VBox(homogeneous=False, spacing=0)
        vbox.show()
        
        # begin entry section
        
        hEntryValueBox = gtk.HBox(False,10)
        #hEntryValueBox.set_sensitive(False)
        hEntryValueBox.show()
        
        labelEntryValue = gtk.Label("Value:")
        labelEntryValue.show() 
        self.entryValue = gtk.Entry()
        self.entryValue.show()
        
        # parameters child, expand, fill, padding
        hEntryValueBox.pack_start(labelEntryValue, False, False, 10)
        hEntryValueBox.pack_start(self.entryValue, True, True, 10)
        
        # end entry section

        ## begin category section

        hCategoryBox = gtk.HBox(False,10)
        hCategoryBox.show()
                        
        labelCategory = gtk.Label("Category")
        labelCategory.show()

        # we use gtk.combo_box_new_text() function because this combo display only text
        # and we can use append_text function
        self.comboBoxCategory = gtk.combo_box_new_text()
        self.comboBoxCategory.show()
        
        # load categories from database
        ##!! check no data
        self.categories = self.sqlUtil.loadCategories()
        for category in self.categories:
            self.comboBoxCategory.append_text(category.description)
        
        hCategoryBox.pack_start(labelCategory, False, False, 10)
        hCategoryBox.pack_start(self.comboBoxCategory, True, True, 10)

        ## end category section 
        
        ## begin from section
        
        hFromBox = gtk.HBox(False,10)
        hFromBox.show()
                        
        labelFrom = gtk.Label("From")
        labelFrom.show()

        self.comboBoxFrom = gtk.combo_box_new_text() 
        self.comboBoxFrom.show()

        hFromBox.pack_start(labelFrom, False, False, 10)
        hFromBox.pack_start(self.comboBoxFrom, True, True, 10)
        
        ## end from section

        ## begin to section
        
        hToBox = gtk.HBox(False,10)
        hToBox.show()
        
        labelTo = gtk.Label("To")
        labelTo.show()

        self.comboBoxTo = gtk.combo_box_new_text() 
        self.comboBoxTo.show()
        
        hToBox.pack_start(labelTo, False, False, 10)
        hToBox.pack_start(self.comboBoxTo, True, True, 10)    
        
        ## end to section
        
        ## begin
        tableResult= gtk.Table(2,1,False)
        tableResult.set_border_width(10)
        tableResult.show()
        
        self.labelResult = gtk.Label("0")
        self.labelResult.show()
        frameLabelResult = gtk.Frame()
        frameLabelResult.set_label("Result ")
        frameLabelResult.set_label_align(0,0.5)
        frameLabelResult.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
        ##TODO ADJUST PROPERTIES
        frameLabelResult.add(self.labelResult)
        frameLabelResult.show()
        
        btConvert = gtk.Button("Convert")
        btConvert.connect("clicked", self.convert)
        btConvert.show()
        
        btClean = gtk.Button("Clean")
        btClean.connect("clicked", self.clean)
        btClean.show()

        tableResult.attach(frameLabelResult,0,2,0,1, ypadding=10)
        tableResult.attach(btConvert,0,1,1,2, ypadding=10)
        tableResult.attach(btClean,1,2,1,2, ypadding=10)
        
        ## end
        
        ## begin virtual keyboard
        keyboardBox = KeyBoard(keyPadMode, self.entryValue) 
        # end virtual keyboard
            
        hButtonsBox = gtk.HButtonBox()
        hButtonsBox.set_layout(gtk.BUTTONBOX_SPREAD)
        hButtonsBox.show()
        
        # signal
        self.comboBoxCategory.connect("changed", self.changeCategory)
        self.comboBoxFrom.connect("changed", self.loadItemsTo)
        
        vbox.pack_start(hEntryValueBox, False, False, 10)
        vbox.pack_start(hCategoryBox, False, False, 10)
        vbox.pack_start(hFromBox, False, False, 10)
        vbox.pack_start(hToBox, False, False, 10)
        vbox.pack_start(tableResult, False, False, 10)
        vbox.pack_start(keyboardBox, False, False,5)

        # count items
        self.countFromItems = 0
        self.countToItems = 0
        
        # first items
        if len(self.categories) != 0:
            self.comboBoxCategory.set_active(0)
            #self.changeCategory(self.comboBoxCategory)

        self.window.add(vbox)
        
    def __init__(self, database, keyPadMode):        
        
        self.sqlUtil = SqlUtil()
        self.sqlUtil.openDatabase(database)
        
        # create a new window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    
        # When the window is given the "delete_event" signal (this is given by the window manager, usually by the "close" option, or on the titlebar), we ask it to call the delete_event () function as defined above. 
        # The data passed to the callback function is NULL and is ignored in the callback function.
        self.window.connect("delete_event", self.delete_event)
    
        # Here we connect the "destroy" event to a signal handler.  
        # This event occurs when we call gtk_widget_destroy() on the window, or if we return FALSE in the "delete_event" callback.
        self.window.connect("destroy", self.destroy)
    
        # Sets the border width of the window.
        self.window.set_border_width(10)
        
        # title
        self.window.set_title("MokoConv")
        
        # size
        self.window.set_default_size(480,640)
        
        self.buildLayout(keyPadMode)
        
        self.window.show()
        
    def main(self):
        
        # All PyGTK applications must have a gtk.main(). Control ends here and waits for an event to occur (like a key press or mouse event).
        gtk.main()
